package activity.setting.PlanVideo;

import android.animation.ObjectAnimator;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.hichip.callback.ICameraIOSessionCallback;
import com.hichip.campro.R;
import com.hichip.content.HiChipDefines;
import com.hichip.control.HiCamera;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import base.HiActivity;
import bean.MyCamera;
import bean.TimeArrayBean;
import butterknife.BindView;
import common.HiDataValue;
import common.TitleView;
import custom.TimeDomainView;
import utils.HiToast;
import utils.HiTools;

public class PlanVideoAdvanceSetActivity extends HiActivity implements View.OnClickListener, ICameraIOSessionCallback {
    @BindView(R.id.title) TitleView title;
    @BindView(R.id.tv_edit) TextView tv_edit;
    private boolean mIsDeleteMode = false;//是否是删除模式

    @BindView(R.id.cb_sunday) CheckBox cb_sunday;
    @BindView(R.id.cb_monday) CheckBox cb_monday;
    @BindView(R.id.cb_tuesday) CheckBox cb_tuesday;
    @BindView(R.id.cb_wednesday) CheckBox cb_wednesday;
    @BindView(R.id.cb_thursday) CheckBox cb_thursday;
    @BindView(R.id.cb_friday) CheckBox cb_friday;
    @BindView(R.id.cb_saturday) CheckBox cb_saturday;

    @BindView(R.id.iv_sunday) ImageView iv_sunday;
    @BindView(R.id.iv_monday) ImageView iv_monday;
    @BindView(R.id.iv_tuesday) ImageView iv_tuesday;
    @BindView(R.id.iv_wednesday) ImageView iv_wednesday;
    @BindView(R.id.iv_thursday) ImageView iv_thursday;
    @BindView(R.id.iv_friday) ImageView iv_friday;
    @BindView(R.id.iv_saturday) ImageView iv_saturday;

    @BindView(R.id.tv_sunday) TextView tv_sunday;
    @BindView(R.id.tv_monday) TextView tv_monday;
    @BindView(R.id.tv_tuesday) TextView tv_tuesday;
    @BindView(R.id.tv_wednesday) TextView tv_wednesday;
    @BindView(R.id.tv_thursday) TextView tv_thursday;
    @BindView(R.id.tv_friday) TextView tv_friday;
    @BindView(R.id.tv_saturday) TextView tv_saturday;

    @BindView(R.id.view_td_sunday) TimeDomainView view_td_sunday;
    @BindView(R.id.view_td_monday) TimeDomainView view_td_monday;
    @BindView(R.id.view_td_tuesday) TimeDomainView view_td_tuesday;
    @BindView(R.id.view_td_wednesday) TimeDomainView view_td_wednesday;
    @BindView(R.id.view_td_thursday) TimeDomainView view_td_thursday;
    @BindView(R.id.view_td_friday) TimeDomainView view_td_friday;
    @BindView(R.id.view_td_saturday) TimeDomainView view_td_saturday;

    @BindView(R.id.ll_sunday) LinearLayout ll_sunday;
    @BindView(R.id.ll_monday) LinearLayout ll_monday;
    @BindView(R.id.ll_tuesday) LinearLayout ll_tuesday;
    @BindView(R.id.ll_wednesday) LinearLayout ll_wednesday;
    @BindView(R.id.ll_thursday) LinearLayout ll_thursday;
    @BindView(R.id.ll_friday) LinearLayout ll_friday;
    @BindView(R.id.ll_saturday) LinearLayout ll_saturday;

    private ArrayList<CheckBox> array_cb;
    private ArrayList<ImageView> array_iv;
    private ArrayList<TextView> array_tv;
    private ArrayList<TimeDomainView> array_tdv;

    @BindView(R.id.ll_function) LinearLayout ll_function;
    @BindView(R.id.tv_application) TextView tv_application;
    private ArrayList<TimeArrayBean> mCheckBeans = new ArrayList<>();

    @BindView(R.id.tv_full_day) TextView tv_full_day;//置为全天
    @BindView(R.id.add_time_domain) TextView add_time_domain;//添加时间域
    @BindView(R.id.tv_empty_day) TextView tv_empty_day;//全天置空

    private MyCamera mMyCamera;

    private HiChipDefines.HI_P2P_QUANTUM_TIME quantum_time;
    private ArrayList<TimeArrayBean> mBeans=new ArrayList<>();

    @Override
    protected int setLayoutId() {
        return R.layout.activity_planvideo_advanceset;
    }

    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        getIntentData();
        initViewAndData();
        setListeners();
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (mMyCamera != null) {
            mMyCamera.registerIOSessionListener(this);
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        if (mMyCamera != null) {
            mMyCamera.unregisterIOSessionListener(this);
        }
    }


    private void setListeners() {
        tv_edit.setOnClickListener(this);

        ll_sunday.setOnClickListener(this);
        ll_monday.setOnClickListener(this);
        ll_tuesday.setOnClickListener(this);
        ll_wednesday.setOnClickListener(this);
        ll_thursday.setOnClickListener(this);
        ll_friday.setOnClickListener(this);
        ll_saturday.setOnClickListener(this);

        tv_full_day.setOnClickListener(this);
        add_time_domain.setOnClickListener(this);
        tv_empty_day.setOnClickListener(this);

        tv_application.setOnClickListener(this);
    }

    private void initViewAndData() {
        title.setTitle(getString(R.string.advance_set));
        title.setButton(TitleView.NAVIGATION_BUTTON_LEFT);
        title.setNavigationBarButtonListener(new TitleView.NavigationBarButtonListener() {
            @Override
            public void OnNavigationButtonClick(int which) {
                switch (which){
                    case TitleView.NAVIGATION_BUTTON_LEFT:
                        finish();
                        break;
                }
            }
        });

        array_cb = new ArrayList<>();
        array_cb.add(cb_sunday);
        array_cb.add(cb_monday);
        array_cb.add(cb_tuesday);
        array_cb.add(cb_wednesday);
        array_cb.add(cb_thursday);
        array_cb.add(cb_friday);
        array_cb.add(cb_saturday);

        array_iv = new ArrayList<>();
        array_iv.add(iv_sunday);
        array_iv.add(iv_monday);
        array_iv.add(iv_tuesday);
        array_iv.add(iv_wednesday);
        array_iv.add(iv_thursday);
        array_iv.add(iv_friday);
        array_iv.add(iv_saturday);

        array_tv = new ArrayList<>();
        array_tv.add(tv_sunday);
        array_tv.add(tv_monday);
        array_tv.add(tv_tuesday);
        array_tv.add(tv_wednesday);
        array_tv.add(tv_thursday);
        array_tv.add(tv_friday);
        array_tv.add(tv_saturday);

        array_tdv = new ArrayList<>();
        array_tdv.add(view_td_sunday);
        array_tdv.add(view_td_monday);
        array_tdv.add(view_td_tuesday);
        array_tdv.add(view_td_wednesday);
        array_tdv.add(view_td_thursday);
        array_tdv.add(view_td_friday);
        array_tdv.add(view_td_saturday);
    }

    private void getIntentData() {
        String str_uid=getIntent().getStringExtra(HiDataValue.EXTRAS_KEY_UID);
        if(!TextUtils.isEmpty(str_uid)){
            for(MyCamera myCamera:HiDataValue.CameraList){
                if(str_uid.equals(myCamera.getUid())){
                    this.mMyCamera =myCamera;
                    break;
                }
            }
        }
        if(HiTools.cameraWhetherNull(mMyCamera,this)) return;
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE, new byte[0]);
    }
    private void handView() {
        for (int i = 0; i < mBeans.size(); i++) {
            TimeArrayBean bean = mBeans.get(i);
            if (bean.mIsAllDay) {
                array_iv.get(i).setSelected(true);
                array_tv.get(i).setText(getString(R.string.full_day_record));
                array_tdv.get(i).drawTimeDomain(bean);
            } else {
                if (bean.arrs.size() > 0) {
                    array_iv.get(i).setSelected(true);
                    array_tv.get(i).setText(bean.arrs.size() +getString(R.string.space_domain));
                    array_tdv.get(i).drawTimeDomain(bean);
                } else {
                    array_tv.get(i).setText("0"+getString(R.string.space_domain));
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_edit:
                handEdit();
                break;
            case R.id.ll_sunday:
                handClickTime(cb_sunday, 0);
                break;
            case R.id.ll_monday:
                handClickTime(cb_monday, 1);
                break;
            case R.id.ll_tuesday:
                handClickTime(cb_tuesday, 2);
                break;
            case R.id.ll_wednesday:
                handClickTime(cb_wednesday, 3);
                break;
            case R.id.ll_thursday:
                handClickTime(cb_thursday, 4);
                break;
            case R.id.ll_friday:
                handClickTime(cb_friday, 5);
                break;
            case R.id.ll_saturday:
                handClickTime(cb_saturday, 6);
                break;
            case R.id.tv_full_day://置为全天
                handFullDay();
                break;
            case R.id.add_time_domain://添加时间域
                handAddTimeDomain();
                break;
            case R.id.tv_empty_day://全天置空
                handEmptyDay();
                break;
            case R.id.tv_application://应用
                //handApplication();
                break;
        }
    }

    private void handApplication() {
        if (quantum_time == null) return;
        for (int i = 0; i < 7; i++) {
            TimeArrayBean bean = mBeans.get(i);
            for (int j = 0; j < 48; j++) {
                quantum_time.sDayData[i][j] = 78;//关
                if (bean.mIsAllDay) {
                    quantum_time.sDayData[i][j] = 80;
                    continue;
                }
                if (bean.getArrs() != null && bean.getArrs().size() < 1 && !bean.mIsAllDay) {
                    quantum_time.sDayData[i][j] = 78;
                    continue;
                }
                for (String strArr : bean.arrs) {
                    String[] strings = strArr.split("-");
                    String strStar = strings[0];
                    String strEnd = strings[1];
                    try {
                        int indexStar = dateToMinute(sdf.parse(strStar)) / 30;
                        int indexEnd = dateToMinute(sdf.parse(strEnd)) / 30 - 1;
                        if (strEnd.equals("23:59")) {
                            indexEnd = 47;
                        }
                        if (j >= indexStar && j <= indexEnd) {
                            quantum_time.sDayData[i][j] = 80;//开
                        }
                    } catch (ParseException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        showjuHuaDialog();
        mMyCamera.sendIOCtrl(HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE, quantum_time.parseContent());
    }

    private void handEmptyDay() {
        if (mCheckBeans.size() > 0) {
            handEdit();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    for (TimeArrayBean bean : mCheckBeans) {
                        bean.arrs.clear();
                        bean.mIsAllDay = false;
                        TimeDomainView tdView = array_tdv.get(bean.title);
                        tdView.drawTimeDomain(bean);
                        if (bean.mIsAllDay) {
                            array_tv.get(bean.title).setText(getString(R.string.full_day_record));
                        } else {
                            array_tv.get(bean.title).setText(bean.arrs.size() +getString(R.string.space_domain));
                            if (bean.arrs.size() < 1) {
                                array_iv.get(bean.title).setSelected(false);
                            }
                        }
                    }
                    handApplication();
                }
            }, 66);//等view 测量完

        } else {
            HiToast.showToast(this, getString(R.string.select_edit_data));
        }
    }

    private void handAddTimeDomain() {
        if (mCheckBeans.size() > 0) {
            Intent intent = new Intent(this, AddTimeDomainActivity.class);
            intent.putExtra(HiDataValue.EXTRAS_KEY_UID,mMyCamera.getUid());
            intent.putParcelableArrayListExtra("beans", mCheckBeans);
            startActivityForResult(intent, 119);
        } else {
            HiToast.showToast(this, getString(R.string.select_edit_data));
        }
    }

    private void handFullDay() {
        if (mCheckBeans.size() > 0) {
            handEdit();
            mHandler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    for (TimeArrayBean bean : mCheckBeans) {
                        bean.mIsAllDay = true;
                        TimeDomainView tdView = array_tdv.get(bean.title);
                        tdView.drawTimeDomain(bean);
                        array_iv.get(bean.title).setSelected(true);
                        array_tv.get(bean.title).setText(getString(R.string.full_day_record));
                    }
                    handApplication();
                }
            }, 66);//等view 测量完
        } else {
            HiToast.showToast(this, getString(R.string.select_edit_data));
        }
    }

    private void handClickTime(CheckBox cb, int value) {
        if (mIsDeleteMode) {
            cb.setChecked(cb.isChecked() ? false : true);
            if (cb.isChecked()) {
                mCheckBeans.add(mBeans.get(value));
            } else {
                mCheckBeans.remove(mBeans.get(value));
            }
        } else {
            Intent intent = new Intent(this, PlanVideoDetailActivity.class);
            intent.putExtra(HiDataValue.EXTRAS_KEY_UID,mMyCamera.getUid());
            if (mBeans != null && mBeans.size() > 0) {
                TimeArrayBean bean = mBeans.get(value);
                intent.putExtra("bean", bean);
                startActivityForResult(intent, 110);
            }
        }
    }


    private void handEdit() {
        mIsDeleteMode = !mIsDeleteMode;
        tv_edit.setText(mIsDeleteMode ? getString(R.string.finish) : getString(R.string.fast_edit));
        cb_sunday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        cb_monday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        cb_tuesday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        cb_wednesday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        cb_thursday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        cb_friday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        cb_saturday.setVisibility(mIsDeleteMode ? View.VISIBLE : View.GONE);
        if (!mIsDeleteMode) {
            for (CheckBox cb : array_cb) {
                cb.setChecked(false);
            }
        }
        int dis = ll_function.getHeight();
        if (mIsDeleteMode) {
            ObjectAnimator animator = ObjectAnimator.ofFloat(ll_function, "translationY", 0f, -dis);
            animator.setDuration(200);
            animator.start();
            tv_application.animate().alpha(0f).setDuration(200).start();
            mCheckBeans.clear();
        } else {
            ObjectAnimator animator = ObjectAnimator.ofFloat(ll_function, "translationY", -dis, 0f);
            animator.setDuration(200);
            animator.start();
            tv_application.animate().alpha(1f).setDuration(200).start();
        }
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL:
                    if (msg.arg2 == 0) {//成功
                        handIOCTRLSuccess(msg);
                    } else {//失败

                    }
                    break;
            }
        }
    };

    private void handIOCTRLSuccess(Message msg) {
        Bundle bundle = msg.getData();
        byte[] data = bundle.getByteArray(HiDataValue.EXTRAS_KEY_DATA);
        switch (msg.arg1) {
            case HiChipDefines.HI_P2P_GET_REC_AUTO_SCHEDULE:
                handData(data);
                handView();
                break;
            case HiChipDefines.HI_P2P_SET_REC_AUTO_SCHEDULE:
                dismissjuHuaDialog();
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case 110:
                    TimeArrayBean myBean = data.getParcelableExtra("bean");
                    mBeans.remove(myBean.title);
                    mBeans.add(myBean.title, myBean);
                    array_tdv.get(myBean.title).drawTimeDomain(myBean);
                    if (myBean.mIsAllDay) {
                        array_tv.get(myBean.title).setText(getString(R.string.full_day_record));
                    } else {
                        array_tv.get(myBean.title).setText(myBean.arrs.size() + getString(R.string.space_domain));
                    }
                    if (myBean.arrs.size() > 0) {
                        array_iv.get(myBean.title).setSelected(true);
                    }
                    break;
                case 119:
                    handEdit();
                    ArrayList<TimeArrayBean> myBeans = data.getParcelableArrayListExtra("beans");
                    for (int i = 0; i < myBeans.size(); i++) {
                        TimeArrayBean bean = myBeans.get(i);
                        mBeans.remove(bean.title);
                        mBeans.add(bean.title, bean);
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                array_tdv.get(bean.title).drawTimeDomain(bean);
                            }
                        },100);
                        if (bean.mIsAllDay) {
                            array_tv.get(bean.title).setText(getString(R.string.full_day_record));
                        } else {
                            array_tv.get(bean.title).setText(bean.arrs.size() + getString(R.string.space_domain));
                        }
                        if (bean.arrs.size() > 0) {
                            array_iv.get(bean.title).setSelected(true);
                        }
                    }
                    break;

            }

        }
    }

    @Override
    public void receiveSessionState(HiCamera hiCamera, int i) {

    }

    @Override
    public void receiveIOCtrlData(HiCamera arg0, int arg1, byte[] arg2, int arg3) {
        if (arg0 != mMyCamera) return;
        Bundle bundle = new Bundle();
        bundle.putByteArray(HiDataValue.EXTRAS_KEY_DATA, arg2);
        Message msg = Message.obtain();
        msg.what = HiDataValue.HANDLE_MESSAGE_RECEIVE_IOCTRL;
        msg.obj = arg0;
        msg.arg1 = arg1;
        msg.arg2 = arg3;
        msg.setData(bundle);
        mHandler.sendMessage(msg);
    }


    private void handData(byte[] data) {
        quantum_time = new HiChipDefines.HI_P2P_QUANTUM_TIME(data);
        byte[][] array = quantum_time.sDayData;
        boolean isStart = false;
        for (int i = 0; i < 7; i++) {
            TimeArrayBean timeArrayBean = new TimeArrayBean();
            boolean isAllDay = true;
            mBeans.add(timeArrayBean);
            timeArrayBean.setTitle(i);
            StringBuffer sb = new StringBuffer();
            for (int j = 0; j < 48; j++) {
                if (array[i][j] == 80) {//80 代表 —P —开
                    isStart = true;
                    if (isStart) {
                        if (TextUtils.isEmpty(sb.toString())) {
                            if(j==47){
                                sb.append("23:30-23:59");
                                timeArrayBean.arrs.add(sb.toString());
                            }else {
                                sb.append(jToStr(j) + "-");
                            }
                        }
                    }
                } else if (array[i][j] == 78) {//78 代表—N—关
                    isAllDay = false;
                    if (isStart) {
                        isStart = false;
                        if (!TextUtils.isEmpty(sb.toString())) {
                            sb.append(jToStr(j));
                            timeArrayBean.arrs.add(sb.toString());
                            sb = new StringBuffer();
                        }
                    }
                }
            }
            timeArrayBean.mIsAllDay = isAllDay;
        }

        for(TimeArrayBean bean:mBeans){
            StringBuffer sb=new StringBuffer();
            for(String str:bean.getArrs()){
                sb.append(str+"   ");
            }
        }
    }

    private String LogData(byte[][] array) {
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < array.length; i++) {
            for (int j = 0; j < array[i].length; j++) {
                sb.append(array[i][j] + ",");
            }
        }
        return sb.toString();
    }

    private SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");

    private String jToStr(int j) {
        Calendar date = Calendar.getInstance();
        date.set(Calendar.HOUR_OF_DAY, 0);
        date.set(Calendar.MINUTE, 0);
        date.set(Calendar.SECOND, 0);
        long timeStamp = date.getTimeInMillis();
        timeStamp = timeStamp + j * 30 * 60 * 1000;
        String str = sdf.format(new Date(timeStamp));
        return str;
    }

    private int dateToMinute(Date date) {
        return date.getHours() * 60 + date.getMinutes();
    }

}
